package com.ruoyi.accountant.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

/***
 *
 */
public class ExchangeRateUtils {
    /***
     * 查询汇率
     * @param fromName
     * @param toName
     * @return
     */
    public static Double exchange(String fromName, String toName, Double money) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("https://data.fixer.io/api/convert?access_key=056f991fc1a1ff2161a09e9a9213f3a1&");
        stringBuilder.append("&from="+fromName);
        stringBuilder.append("&to="+toName);
        stringBuilder.append("&amount="+money);

//        URLConnection urlConnection = new URL(stringBuilder.toString()).openConnection();
//        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
//        String s = bufferedReader.readLine();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map map = objectMapper.readValue(new URL(stringBuilder.toString()), Map.class);
            System.out.println(map.get("result"));
            return Double.valueOf(String.valueOf(map.get("result")));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(ExchangeRateUtils.exchange("USD", "EUR", 25D));
    }
}
